package com.v1.admin.action;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.v1.admin.manage.Feed;
import com.v1.cache.CategoryCache;
import com.v1.lo.CategoryTran;
import com.v1.model.Category;
import com.v1.model.CategoryWapper;
import com.v1.model.ItemWapper;

public class CategoryAction extends AdminAction {
	public ActionForward unspecified(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		CategoryCache categoryCache = (CategoryCache) getBean("CategoryCache");
		List<Category> allCategorys = categoryCache.getAllCategorys();
		setAttribute(request, "allCategorys", allCategorys);
		return mapping.findForward("category");
	}

	public ActionForward add(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		try {
			String from = getString(request, "from", true);
			Feed feed = (Feed) getBean(from);
			String url = getString(request, "url", true);
			CategoryWapper categoryWapper = feed.parse(url);

			String name = getString(request, "name", true, null);
			String digest = getString(request, "digest", true, null);
			String author = getString(request, "author", true, null);
			String thumb = getString(request, "thumb", true, null);
			Integer parentid = getInteger(request, "parentid", 0, true);
			String jsp = getString(request, "jsp", true, null);
			categoryWapper.setName(StringUtils.defaultString(name, categoryWapper.getName()));
			categoryWapper.setDigest(StringUtils.defaultString(digest, categoryWapper.getDigest()));
			if (StringUtils.isEmpty(thumb)) {
				if (StringUtils.isEmpty(categoryWapper.getThumb())
						|| CategoryWapper.NOT_EXIST_THUMB.equals(categoryWapper.getThumb())) {
					List<ItemWapper> items = categoryWapper.getItems();
					if (CollectionUtils.isEmpty(items)) {
						thumb = CategoryWapper.NOT_EXIST_THUMB;
					} else {
						thumb = items.get(0).getThumb();
					}
				} else {
					thumb = categoryWapper.getThumb();
				}
			}
			categoryWapper.setThumb(thumb);
			categoryWapper.setAuthor(author);
			categoryWapper.setParentid(parentid);
			categoryWapper.setJsp(jsp);

			CategoryTran categoryTran = (CategoryTran) getBean("CategoryTran");
			categoryTran.addCategoryTran(categoryWapper);
			setAttribute(request, "message", "ok, done.");
		} catch (Exception e) {
			log.debug(e.getMessage(), e);
			setAttribute(request, "message", "ops." + e.getMessage());
		}

		return unspecified(mapping, form, request, response);
	}
}
